package com.ruyuan2020.im.design.observerdesignpattern;

import java.util.ArrayList;
import java.util.List;

// 具体主题类
public class ConcreteSubject implements Subject {
    // 维护一个观察者列表
    private List<Observer> observers = new ArrayList<>();
    private String subjectState;

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers(String state) {
        // 遍历观察者列表并通知每个观察者
        for (Observer observer : observers) {
            observer.update(state);
        }
    }

    // 设置主题状态的方法，状态改变时通知观察者
    public void setState(String state) {
        this.subjectState = state;
        notifyObservers(state);
    }

    public String getState() {
        return subjectState;
    }
}
